package com.unf.edu.rms.controller.faculty;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.unf.edu.rms.controller.userlogin.UserLoginController;
import com.unf.edu.rms.controller.users.RMSBaseController;
import com.unf.edu.rms.controller.validation.FacultyValidator;
import com.unf.edu.rms.dao.Faculty;
import com.unf.edu.rms.dao.Student;
import com.unf.edu.rms.dao.Thesis;
import com.unf.edu.rms.dao.ThesisCommittee;
import com.unf.edu.rms.dao.ThesisToThesisStatus;
import com.unf.edu.rms.service.FacultyService;
import com.unf.edu.rms.service.ThesisService;
import com.unf.edu.rms.service.StudentService;
import com.unf.edu.rms.util.DateUtil;
import com.unf.edu.rms.util.RMSConstants;

@Controller
public class FacultyController extends RMSBaseController{

	@Autowired
	private ThesisService thesisService;
	@Autowired
	private StudentService studentService;
	@Autowired
	private FacultyService facultyService;
	@Autowired
	private UserLoginController userLoginController;
	
	@RequestMapping("/viewFacultyList")
	public String viewFacultyList(Model model) {
		int roleId = userLoginController.checkValidateSession();
		if(roleId==0){
			return "redirect:Dashboard.html";
		}
		System.out.println("FacultyController.viewFacultyList()==========");
		List<Faculty> facultyList = facultyService.getFacultyList();
		model.addAttribute("facultyList", facultyList);
		return RMSConstants.FACULTY_LIST_VIEW;
	}
	
	@RequestMapping("/printFacultyList")
	public String printFacultyList(Model model) {
		int roleId = userLoginController.checkValidateSession();
		if(roleId==0){
			return "redirect:Dashboard.html";
		}
		System.out.println("FacultyController.viewFacultyList()==========");
		List<Faculty> facultyList = facultyService.getFacultyList();
		model.addAttribute("facultyList", facultyList);
		return RMSConstants.FACULTY_LIST_PRINT;
	}
	
	@RequestMapping(value = "/viewNewFaculty", method = RequestMethod.POST)
	public String viewNewFaculty(@ModelAttribute("faculty") Faculty faculty,Model model) {
		int roleId = userLoginController.checkValidateSession();
		if(roleId==0){
			return "redirect:Dashboard.html";
		}
		
		List<Student> studentList = studentService.viewStudentTable();
		List<Faculty> facultyList = facultyService.getFacultyList();
		Map<Integer,String> nNumberMap = new HashMap<Integer, String>();
		int i = 0;
		for(Student studentx:studentList)
		{
			if(studentx.getNnumber() != null && studentx.getNnumber() != ""){
				nNumberMap.put(i++,studentx.getNnumber());
			}
		}
		
		for(Faculty facultyx:facultyList)
		{
			if(facultyx.getNnumber() != null && facultyx.getNnumber() != ""){
				nNumberMap.put(i++, facultyx.getNnumber());
			}
		}
		model.addAttribute("nNumberMap", nNumberMap);
		
		return RMSConstants.ADD_FACULTY_VIEW;
	}
	
	@RequestMapping(value = "/addNewFaculty", method = RequestMethod.POST)
	public String addNewFaculty(@ModelAttribute("faculty") Faculty faculty,BindingResult bindingResult,Model model) {
		System.out.println("FacultyController.addNewFaculty()==========");
		
		FacultyValidator facultyValidator = new FacultyValidator();
		facultyValidator.validate(faculty, bindingResult);
		//Validate the E-mail Address to ensure that it is valid
		if(!checkEmail(faculty.getEmail())){
			bindingResult.rejectValue("email", "error.email.invalid");
		}
		if(!bindingResult.hasErrors()){
			facultyService.addNewFaculty(faculty);
			return "redirect:viewFacultyList.html";
		}
		else{
			
			List<Student> studentList = studentService.viewStudentTable();
			List<Faculty> facultyList = facultyService.getFacultyList();
			Map<Integer,String> nNumberMap = new HashMap<Integer, String>();
			int i = 0;
			for(Student studentx:studentList)
			{
				if(studentx.getNnumber() != null && studentx.getNnumber() != ""){
					nNumberMap.put(i++,studentx.getNnumber());
				}
			}
			
			for(Faculty facultyx:facultyList)
			{
				if(facultyx.getNnumber() != null && facultyx.getNnumber() != ""){
					nNumberMap.put(i++, facultyx.getNnumber());
				}
			}
			model.addAttribute("nNumberMap", nNumberMap);
			
			return RMSConstants.ADD_FACULTY_VIEW;
		}
	}
	
	@RequestMapping(value = "/viewExistingFaculty", method = RequestMethod.POST)
	public String viewExitingFaculty(@RequestParam(required=true) int facultyId,Model model) {
		int roleId = userLoginController.checkValidateSession();
		if(roleId==0){
			return "redirect:Dashboard.html";
		}
		Faculty faculty = facultyService.getFacultyById(facultyId);
		model.addAttribute("faculty",faculty);
		
		List<Student> studentList = studentService.viewStudentTable();
		List<Faculty> facultyList = facultyService.getFacultyList();
		
		Map<Integer,String> nNumberMap = new HashMap<Integer, String>();
		int i = 0;
		for(Student studentx:studentList)
		{
			if(studentx.getNnumber() != null && studentx.getNnumber() != ""){
				nNumberMap.put(i++,studentx.getNnumber());
			}
		}
		
		for(Faculty facultyx:facultyList)
		{
			if(facultyx.getNnumber() != null && facultyx.getNnumber() != ""){
				nNumberMap.put(i++, facultyx.getNnumber());
			}
		}
		model.addAttribute("nNumberMap", nNumberMap);
		
		return RMSConstants.ADD_FACULTY_VIEW;
	}
	
	/**
	 * This method updates the exisiting faculty
	 * @param faculty
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/updateFaculty", method = RequestMethod.POST)
	public String updateFaculty(@RequestParam(required=true) int facultyId,@ModelAttribute("faculty") Faculty faculty,BindingResult bindingResult,Model model) {
		
		FacultyValidator facultyValidator = new FacultyValidator();
		facultyValidator.validate(faculty, bindingResult);
		//Validate the E-mail Address to ensure that it is valid
		if(!checkEmail(faculty.getEmail())){
			bindingResult.rejectValue("email", "error.email.invalid");
		}
		if(!bindingResult.hasErrors()){
			faculty.setFacultyId(facultyId);
			System.out.println("FacultyController.updateFaculty()=========="+faculty.getFacultyId());
			facultyService.updateFaculty(faculty);
			return "redirect:viewFacultyList.html";
		}
		else{
			return RMSConstants.ADD_FACULTY_VIEW;
		}
	}
	
	@RequestMapping(value = "/viewFacultyDetails", method = RequestMethod.POST)
    public String viewFacultyDetails(@RequestParam(required=true) int facultyId, Model model){
		int roleId = userLoginController.checkValidateSession();
		if(roleId==0){
			return "redirect:Dashboard.html";
		}
		
		List<Thesis> thesisList = thesisService.getThesisList();
		List<Thesis> committeeList = new LinkedList<Thesis>();
		System.out.println(facultyId);
		
		for(int i=0; i < thesisList.size(); i++){
			
			Thesis thesis = thesisList.get(i);
			Set<ThesisCommittee> thesisCommittees = thesis.getThesisCommittees();
	        int count=0;
	    	for(ThesisCommittee thesisCommittee:thesisCommittees){
	    		if(thesisCommittee.getFacultyByCommitteeChair()!=null){
	        		thesis.setThesisChairId(Integer.toString(thesisCommittee.getFacultyByCommitteeChair().getFacultyId()));
	        		thesis.setThesisChairName(thesisCommittee.getFacultyByCommitteeChair().getFullName());
	    		}
	    		
	    		if(thesisCommittee.getFacultyByCommitteeMember1()!=null){
	    			thesis.setCommitteeMember1Id(Integer.toString(thesisCommittee.getFacultyByCommitteeMember1().getFacultyId()));
	    			thesis.setCommitteeMember1Name(thesisCommittee.getFacultyByCommitteeMember1().getFullName());
	    		
	    		}
	    		
	    		if(thesisCommittee.getFacultyByCommitteeMember2()!=null){
	    			thesis.setCommitteeMember2Id(Integer.toString(thesisCommittee.getFacultyByCommitteeMember2().getFacultyId()));
	    			thesis.setCommitteeMember2Name(thesisCommittee.getFacultyByCommitteeMember2().getFullName());
	    		
	    		}
	    		
	    		if(thesisCommittee.getFacultyByCommitteeMember3()!=null){
	    			thesis.setCommitteeMember3Id(Integer.toString(thesisCommittee.getFacultyByCommitteeMember3().getFacultyId()));
	    			thesis.setCommitteeMember3Name(thesisCommittee.getFacultyByCommitteeMember3().getFullName());
	    		
	    		}
	    		
	    		if(thesisCommittee.getFacultyByCommitteeMember4()!=null){
	    			thesis.setCommitteeMember4Id(Integer.toString(thesisCommittee.getFacultyByCommitteeMember4().getFacultyId()));
	    			thesis.setCommitteeMember4Name(thesisCommittee.getFacultyByCommitteeMember4().getFullName());
	    		
	    		}
	    	}
	    	
	    	
	    	Set<ThesisToThesisStatus> thesisToThesisStatuses = thesis.getThesisToThesisStatuses();
	    	/*for(ThesisToThesisStatus status:thesisToThesisStatuses)
			{
				System.out.println("ThesisController.viewExistingThesis()======status.getThesisStatus().getProspectus()========"+status.getThesisStatus().getProspectusPassed());
				System.out.println("ThesisController.viewExistingThesis()======status.getThesisStatus().getProspectusPassed()========"+status.getThesisStatus().getProspectusPassed());
				//prospectus details
				
				thesis.setProspectusDateStr(status.getThesisStatus().getProspectusDate()!=null?DateUtil.dateToStr(status.getThesisStatus().getProspectusDate()):"");
				thesis.setProspectusPassed(status.getThesisStatus().getProspectusPassed());
				// defense details
				thesis.setDefenseDateStr(status.getThesisStatus().getDefenseDate()!=null?DateUtil.dateToStr(status.getThesisStatus().getDefenseDate()):"");
				thesis.setDefensePassed(status.getThesisStatus().getDefensePassed());
				thesis.setComments(status.getThesisStatus().getComments());
			}*/
	 		//model.addAttribute("studentList", studentMap);
			thesis.setCategoryStr(thesis.getCategory().getCategoryName());
			//System.out.println(thesisCommittee.size());
			
			String thesisStatusOverviewString = "";
			//Set<ThesisToThesisStatus> thesisToThesisStatuses = thesis.getThesisToThesisStatuses();
			System.out.println("ThesisController.viewThesisList()======thesis Id======"+thesis.getThesisId());
			for(ThesisToThesisStatus status:thesisToThesisStatuses)
			{
				if(status.getThesisStatus().getEnrolled().charAt(0)=='Y' || status.getThesisStatus().getEnrolled().charAt(0)=='y'){
					thesisStatusOverviewString = "Enrolled in Thesis";
				}
				if(status.getThesisStatus().getProspectusPassed().charAt(0)=='Y' || status.getThesisStatus().getProspectusPassed().charAt(0)=='y')
				{
					thesisStatusOverviewString = ("Prospectus completed");
				}
				if(status.getThesisStatus().getDefensePassed().charAt(0)=='Y'||status.getThesisStatus().getDefensePassed().charAt(0)=='y')
				{
					thesisStatusOverviewString = ("Defense completed");
				}
				if(status.getThesisStatus().getSubmittedDirector().charAt(0)=='Y' || status.getThesisStatus().getSubmittedDirector().charAt(0)=='y')
				{
					thesisStatusOverviewString = ("Submitted to SoC Director");
				}
				if(status.getThesisStatus().getSubmittedDean().charAt(0)=='Y' || status.getThesisStatus().getSubmittedDean().charAt(0)=='y')
				{
					thesisStatusOverviewString = ("Submitted to CCEC Dean");
				}
				if(status.getThesisStatus().getSubmittedGradDean().charAt(0)=='Y' || status.getThesisStatus().getSubmittedGradDean().charAt(0)=='y')
				{
					thesisStatusOverviewString = ("Submitted to Graduate Dean");
				}
				if(status.getThesisStatus().getSubmittedLibrary().charAt(0)=='Y' || status.getThesisStatus().getSubmittedLibrary().charAt(0)=='y')
				{
					thesisStatusOverviewString = ("Submitted to SoC Library");
				}
				
			}
			thesis.setThesisStatusOverviewString(thesisStatusOverviewString);
			
			System.out.println("Thesis: " + thesis.getThesisId() + "   Chair: " + thesis.getThesisChairId() + "  " + thesis.getThesisChairName());
			if( thesis.getThesisChairId()!=null && thesis.getThesisChairId().length() > 0 && Integer.parseInt(thesisList.get(i).getThesisChairId())==facultyId ){
				committeeList.add(thesis);
			}
			else if(thesis.getCommitteeMember1Id()!=null && thesis.getCommitteeMember1Id().length() > 0 && Integer.parseInt(thesis.getCommitteeMember1Id())==facultyId){
				committeeList.add(thesis);
			}
			else if(thesis.getCommitteeMember2Id()!=null && thesis.getCommitteeMember2Id().length() > 0 && Integer.parseInt(thesis.getCommitteeMember2Id())==facultyId){
				committeeList.add(thesis);
			}
			else if(thesis.getCommitteeMember3Id()!=null && thesis.getCommitteeMember3Id().length() > 0 && Integer.parseInt(thesis.getCommitteeMember3Id())==facultyId){
				committeeList.add(thesis);
			}
			else if(thesis.getCommitteeMember4Id()!=null && thesis.getCommitteeMember4Id().length() > 0 && Integer.parseInt(thesis.getCommitteeMember4Id())==facultyId){
				committeeList.add(thesis);
			}
		}
	
		System.out.println("Thesis Committee List Size===================" + committeeList.size());
		for(int j = 0; j < committeeList.size(); j++){
			System.out.println(committeeList.get(j).getTitle() + " " + committeeList.get(j).getStudent());
		}
		
        Faculty faculty = facultyService.getFacultyById(facultyId);
        model.addAttribute("faculty", faculty);
        model.addAttribute("committeeList", committeeList);
        return RMSConstants.FACULTY_DETAILS_VIEW;
    }
	
	@RequestMapping(value = "/printFacultyDetails", method = RequestMethod.POST)
    public String printFacultyDetails(@RequestParam(required=true) int facultyId, Model model){
		int roleId = userLoginController.checkValidateSession();
		if(roleId==0){
			return "redirect:Dashboard.html";
		}
		
		List<Thesis> thesisList = thesisService.getThesisList();
		List<Thesis> committeeList = new LinkedList<Thesis>();
		System.out.println(facultyId);
		
		for(int i=0; i < thesisList.size(); i++){
			
			Thesis thesis = thesisList.get(i);
			Set<ThesisCommittee> thesisCommittees = thesis.getThesisCommittees();
	        int count=0;
	    	for(ThesisCommittee thesisCommittee:thesisCommittees){
	    		if(thesisCommittee.getFacultyByCommitteeChair()!=null){
	        		thesis.setThesisChairId(Integer.toString(thesisCommittee.getFacultyByCommitteeChair().getFacultyId()));
	        		thesis.setThesisChairName(thesisCommittee.getFacultyByCommitteeChair().getFullName());
	    		}
	    		
	    		if(thesisCommittee.getFacultyByCommitteeMember1()!=null){
	    			thesis.setCommitteeMember1Id(Integer.toString(thesisCommittee.getFacultyByCommitteeMember1().getFacultyId()));
	    			thesis.setCommitteeMember1Name(thesisCommittee.getFacultyByCommitteeMember1().getFullName());
	    		
	    		}
	    		
	    		if(thesisCommittee.getFacultyByCommitteeMember2()!=null){
	    			thesis.setCommitteeMember2Id(Integer.toString(thesisCommittee.getFacultyByCommitteeMember2().getFacultyId()));
	    			thesis.setCommitteeMember2Name(thesisCommittee.getFacultyByCommitteeMember2().getFullName());
	    		
	    		}
	    		
	    		if(thesisCommittee.getFacultyByCommitteeMember3()!=null){
	    			thesis.setCommitteeMember3Id(Integer.toString(thesisCommittee.getFacultyByCommitteeMember3().getFacultyId()));
	    			thesis.setCommitteeMember3Name(thesisCommittee.getFacultyByCommitteeMember3().getFullName());
	    		
	    		}
	    		
	    		if(thesisCommittee.getFacultyByCommitteeMember4()!=null){
	    			thesis.setCommitteeMember4Id(Integer.toString(thesisCommittee.getFacultyByCommitteeMember4().getFacultyId()));
	    			thesis.setCommitteeMember4Name(thesisCommittee.getFacultyByCommitteeMember4().getFullName());
	    		
	    		}
	    	}
	    	
	    	
	    	Set<ThesisToThesisStatus> thesisToThesisStatuses = thesis.getThesisToThesisStatuses();
//	    	for(ThesisToThesisStatus status:thesisToThesisStatuses)
//			{
//				System.out.println("ThesisController.viewExistingThesis()======status.getThesisStatus().getProspectus()========"+status.getThesisStatus().getProspectusPassed());
//				System.out.println("ThesisController.viewExistingThesis()======status.getThesisStatus().getProspectusPassed()========"+status.getThesisStatus().getProspectusPassed());
//				//prospectus details
//				thesis.setProspectusDateStr(status.getThesisStatus().getProspectusDate()!=null?DateUtil.dateToStr(status.getThesisStatus().getProspectusDate()):"");
//				thesis.setProspectusPassed(status.getThesisStatus().getProspectusPassed());
//				// defense details
//				thesis.setDefenseDateStr(status.getThesisStatus().getDefenseDate()!=null?DateUtil.dateToStr(status.getThesisStatus().getDefenseDate()):"");
//				thesis.setDefensePassed(status.getThesisStatus().getDefensePassed());
//				thesis.setComments(status.getThesisStatus().getComments());
//			}
	 		//model.addAttribute("studentList", studentMap);
			thesis.setCategoryStr(thesis.getCategory().getCategoryName());
			//System.out.println(thesisCommittee.size());
			
			String thesisStatusOverviewString = "";
			//Set<ThesisToThesisStatus> thesisToThesisStatuses = thesis.getThesisToThesisStatuses();
			System.out.println("ThesisController.viewThesisList()======thesis Id======"+thesis.getThesisId());
			for(ThesisToThesisStatus status:thesisToThesisStatuses)
			{
				if(status.getThesisStatus().getEnrolled().charAt(0)=='Y' || status.getThesisStatus().getEnrolled().charAt(0)=='y'){
					thesisStatusOverviewString = "Enrolled in Thesis";
				}
				if(status.getThesisStatus().getProspectusPassed().charAt(0)=='Y' || status.getThesisStatus().getProspectusPassed().charAt(0)=='y')
				{
					thesisStatusOverviewString = ("Prospectus completed");
				}
				if(status.getThesisStatus().getDefensePassed().charAt(0)=='Y'||status.getThesisStatus().getDefensePassed().charAt(0)=='y')
				{
					thesisStatusOverviewString = ("Defense completed");
				}
				if(status.getThesisStatus().getSubmittedDirector().charAt(0)=='Y' || status.getThesisStatus().getSubmittedDirector().charAt(0)=='y')
				{
					thesisStatusOverviewString = ("Submitted to SoC Director");
				}
				if(status.getThesisStatus().getSubmittedDean().charAt(0)=='Y' || status.getThesisStatus().getSubmittedDean().charAt(0)=='y')
				{
					thesisStatusOverviewString = ("Submitted to CCEC Dean");
				}
				if(status.getThesisStatus().getSubmittedGradDean().charAt(0)=='Y' || status.getThesisStatus().getSubmittedGradDean().charAt(0)=='y')
				{
					thesisStatusOverviewString = ("Submitted to Graduate Dean");
				}
				if(status.getThesisStatus().getSubmittedLibrary().charAt(0)=='Y' || status.getThesisStatus().getSubmittedLibrary().charAt(0)=='y')
				{
					thesisStatusOverviewString = ("Submitted to SoC Library");
				}
				
			}
			thesis.setThesisStatusOverviewString(thesisStatusOverviewString);
			
			System.out.println("Thesis: " + thesis.getThesisId() + "   Chair: " + thesis.getThesisChairId() + "  " + thesis.getThesisChairName());
			if( thesis.getThesisChairId()!=null && thesis.getThesisChairId().length() > 0 && Integer.parseInt(thesisList.get(i).getThesisChairId())==facultyId ){
				committeeList.add(thesis);
			}
			else if(thesis.getCommitteeMember1Id()!=null && thesis.getCommitteeMember1Id().length() > 0 && Integer.parseInt(thesis.getCommitteeMember1Id())==facultyId){
				committeeList.add(thesis);
			}
			else if(thesis.getCommitteeMember2Id()!=null && thesis.getCommitteeMember2Id().length() > 0 && Integer.parseInt(thesis.getCommitteeMember2Id())==facultyId){
				committeeList.add(thesis);
			}
			else if(thesis.getCommitteeMember3Id()!=null && thesis.getCommitteeMember3Id().length() > 0 && Integer.parseInt(thesis.getCommitteeMember3Id())==facultyId){
				committeeList.add(thesis);
			}
			else if(thesis.getCommitteeMember4Id()!=null && thesis.getCommitteeMember4Id().length() > 0 && Integer.parseInt(thesis.getCommitteeMember4Id())==facultyId){
				committeeList.add(thesis);
			}
		}
		
		System.out.println("Thesis Committee List Size===================" + committeeList.size());
		for(int j = 0; j < committeeList.size(); j++){
			System.out.println(committeeList.get(j).getTitle() + " " + committeeList.get(j).getStudent());
		}
		
        Faculty faculty = facultyService.getFacultyById(facultyId);
        model.addAttribute("faculty", faculty);
        model.addAttribute("committeeList", committeeList);
        return RMSConstants.FACULTY_DETAILS_PRINT;
    }
	
	//This Method checks the email string against the regular expression that forms a standard email address
	public boolean checkEmail(String email)
	{
		System.out.println("Checking the validity of the e-mail.");
		String emailPattern = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
		+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
		Pattern pattern = Pattern.compile(emailPattern);
		Matcher matcher = pattern.matcher(email);
		System.out.println("Email Address: " + email + "    Is it valid?! " + matcher.matches());
	
		return matcher.matches();
	}
}


